<?php

namespace RoleUser\Listener;

use Zend\EventManager\EventManagerInterface;
use Zend\EventManager\ListenerAggregateInterface;
use Zend\ServiceManager\ServiceLocatorInterface;

use RoleUser\Mapper\RoleInterface;
use RoleUser\Service\RoleAdminUser as RoleAdminUser;

class SendListener implements ListenerAggregateInterface {

    /**
     * @var \Zend\Stdlib\CallbackHandler[]
     */
    protected $listeners = array();
    protected $roleMapper;
    
    protected $serviceLocator;
    
    public function __construct(ServiceLocatorInterface $serviceLocator) {
        $this->serviceLocator = $serviceLocator;
    }
    /**
     * {@inheritDoc}
     */
    public function attach(EventManagerInterface $events) {
        $sharedEvents = $events->getSharedManager();
        $this->listeners[] = $sharedEvents->attach('Admin\Service\AdminUser', 'createUser', array($this, 'onCreateUser'), 100);
    }

    public function detach(EventManagerInterface $events) {
        foreach ($this->listeners as $index => $listener) {
            if ($events->detach($listener)) {
                unset($this->listeners[$index]);
            }
        }
    }

    public function onCreateUser($e) 
    {
        //die(print_r($this->serviceLocator->get('user_role_mapper')));
        $user = $e->getParams('user');
        $user = $user['user'];
        if($user) {
            /*---------------------------Role_User-----------------------------------------*/
            $userRole = $user->getRoleUserLinker();
            $userRole->setUserid($user->getUserId());
            /*---------------------------Role_User-----------------------------------------*/
            $this->getRoleMapper()->insert($userRole);
            //$this->getRoleMapper()->insert($userRole);
        }
        return $user;
    }
    
     public function setRoleMapper(RoleInterface $roleMapper)
    {
        $this->roleMapper = $roleMapper;
        return $this;
    }

    public function getRoleMapper()
    {
        if (null === $this->roleMapper) {
            $this->roleMapper = $this->serviceLocator->get('user_role_mapper');
        }
        return $this->roleMapper;

    }

}
